<template>
  <el-dialog
    width="900px"
    :visible.sync="visible"
    :title="`${isUpdate ? '编辑' : '添加'}成员`"
    destroy-on-close
    :close-on-click-modal="false"
    append-to-body
    @close="close"
  >
    <AddOrUpdateUserForm
      ref="form"
      :model="formValue"
      :is-update="isUpdate"
    ></AddOrUpdateUserForm>
    <template #footer>
      <div class="controls text-center">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" plain @click="save(false)"
          >保存并继续添加</el-button
        >
        <el-button type="primary" @click="save(true)">保存</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts">
import Vue from 'vue'
// import cloneDeep from 'lodash/cloneDeep'
import cloneDeep from 'lodash/cloneDeep'
import AddOrUpdateUserForm from './AddOrUpdateUserForm.vue'
import { upsertUser } from '@/api/user.ts'

const initFormValue = {
  account: '',
  accountName: '',
  email: '',
  gender: '',
  iconUrl: '',
  id: '',
  password: '',
  phone: '',
  position: '',
  roleIds: [],
  // wechart: '',
  wechat: '',
  org: null,
}

export default Vue.extend({
  name: 'AddOrUpdateUserDialog',
  components: { AddOrUpdateUserForm },
  data() {
    return {
      visible: false,
      formValue: cloneDeep(initFormValue),
      isUpdate: false,
    }
  },
  methods: {
    close() {
      this.$refs.form?.resetFields()

      Object.assign(this.formValue, initFormValue)
      /// this.
      this.visible = false
    },
    // 其实这是懒惰的做法，好的做法是 .sync 再利用 'proxy'
    show(row) {
      if (row) {
        console.log(row)
        Object.assign(this.formValue, row, {
          org: {
            orgName: row.orgName,
            id: row.orgId,
          },
        })
        this.isUpdate = true
      } else {
        this.isUpdate = false
      }
      this.visible = true
    },
    async save(flag: boolean) {
      try {
        await this.$refs.form.validate()
        const params = {
          ...this.formValue,
          orgId: this.formValue.org?.id, // orgId,
          iconUrl: [{}],
          orgName: this.formValue.org?.orgName,
        }
        delete params.org
        await upsertUser(params)
        if (flag) {
          this.close()
        } else {
          this.$refs.form.resetFields()
        }
        // this.$refs.form.resetFields()
        this.$message.success(`${this.isUpdate ? '修改' : '新增'}用户成功!`)
        this.$emit('success')
      } catch (error) {
        // 验证
        console.log(error)
      }

      // form.
    },
  },
})
</script>

<style></style>
